import numpy as np
import os


######################################################################
# ##########BCG信号处理部分###########################################
# 去除解相位出错的bcg信号
def remove_bcg_distortion(raw_data):
    """
    去除解相位错误得到的信号
    :param raw_data 输入信号
    :type array
    """
    filtered_raw_data = np.copy(raw_data)
    length = len(filtered_raw_data)
    # 差分信号的阈值
    threshold = [-0.5, 0.5]
    # 求信号导数
    delta_raw_data = np.zeros((length,))
    delta_raw_data[1:] = raw_data[1:] - raw_data[:-1]
    # 我们默认至少前1个点不是畸变点
    if_distortion = np.zeros((length,))
    for n in range(len(delta_raw_data)):
        # 判断该点是否为相位畸变点
        if delta_raw_data[n] > threshold[1]:
            # 如果该点是正跳变点,将后面的所有点下移
            if_distortion[n] = 1

            # 计算下移长度：畸变点导数值-畸变点前5个正常点的导数值的平均值
            normal_points = np.argwhere(if_distortion[:n] == 0)
            normal_delta = np.mean(delta_raw_data[normal_points[-5:]])
            move_down = delta_raw_data[n]

            # 畸变点之后的所有点下移
            filtered_raw_data[n:] = filtered_raw_data[n:] - move_down + normal_delta
        if delta_raw_data[n] < threshold[0]:
            # 如果该点是负跳变点,将后面的所有点上移
            if_distortion[n] = 1
            normal_points = np.argwhere(if_distortion[:n] == 0)
            normal_delta = np.mean(delta_raw_data[normal_points[-5:]])
            move_up = delta_raw_data[n]
            filtered_raw_data[n:] = filtered_raw_data[n:] - move_up + normal_delta
    return filtered_raw_data


def extract_heart_signal(bcg, fs):
    # 去除呼吸信号
    # f1 = 1
    # f2 = 15
    # w1 = f1 / fs *2
    # w2 = f2 / fs *2
    # b, a = signal.butter(3, [w1, w2], 'bandpass')
    # bcg = signal.filtfilt(b, a, bcg)
    return bcg
